BOARD := raspi4b

QEMU_BIN := /home/user/qemu/qemu_install/bin/qemu-system-aarch64
QEMU_FLAGS := -machine $(BOARD) -nographic

TOOLCHAIN_PREFIX := /home/user/qemu/gcc-arm/bin/aarch64-none-linux-gnu

CC := $(TOOLCHAIN_PREFIX)-gcc
COPS   += -g -Wall -nostdlib -Iinclude -O0 -mgeneral-regs-only -Wno-builtin-declaration-mismatch

AS := $(TOOLCHAIN_PREFIX)-as
ASMOPS += -g -Iinclude 

LINKER := $(TOOLCHAIN_PREFIX)-ld
OBJCOPY := $(TOOLCHAIN_PREFIX)-objcopy

BUILD_DIR = build
SRC_DIR = src

all : cos.bin

clean :
	rm -rf $(BUILD_DIR) *.bin 

$(BUILD_DIR)/%_c.o: $(SRC_DIR)/%.c
	mkdir -p $(@D)
	$(CC) $(COPS) -c $< -o $@

$(BUILD_DIR)/%_s.o: $(SRC_DIR)/%.S
	$(CC) $(ASMOPS) -c $< -o $@

C_FILES = $(wildcard $(SRC_DIR)/*.c)
OBJ_FILES = $(C_FILES:$(SRC_DIR)/%.c=$(BUILD_DIR)/%_c.o)

ASM_FILES = $(wildcard $(SRC_DIR)/*.S)
OBJ_FILES += $(ASM_FILES:$(SRC_DIR)/%.S=$(BUILD_DIR)/%_s.o)

cos.bin: $(SRC_DIR)/linker.ld $(OBJ_FILES)
	$(LINKER) -T $(SRC_DIR)/linker.ld -o $(BUILD_DIR)/cos.elf  $(OBJ_FILES) -e _start
	$(OBJCOPY) $(BUILD_DIR)/cos.elf -O binary cos.bin
	nm $(BUILD_DIR)/cos.elf | sort > cos_map

run:
	$(QEMU_BIN) $(QEMU_FLAGS) -kernel cos.bin
debug:
	$(QEMU_BIN) $(QEMU_FLAGS) -kernel cos.bin -gdb tcp::1234 -S
